package com.study.springmvc.servlet;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author lupengwei 2021/5/17 10:19
 */
public class Handler {
    
    private Object controllerObject;
    
    private Method method;
    
    private List<String> paramNameList;
    
    public Object getControllerObject() {
        return controllerObject;
    }
    
    public void setControllerObject(Object controllerObject) {
        this.controllerObject = controllerObject;
    }
    
    public Method getMethod() {
        return method;
    }
    
    public void setMethod(Method method) {
        this.method = method;
    }
    
    public List<String> getParamNameList() {
        return paramNameList;
    }
    
    public void setParamNameList(List<String> paramNameList) {
        this.paramNameList = paramNameList;
    }
    
    public Object invoke(Map<String, Object> paramMap) {
        List<Object> paramValueList = new ArrayList<>();
        for (String paramName : paramNameList) {
            Object paramValue = paramMap.get(paramName);
            paramValueList.add(paramValue);
        }
        
        try {
            return method.invoke(controllerObject, paramValueList.toArray(new Object[0]));
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
